import React, { useEffect } from "react";

import * as THREE from "three";

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

import { TransformControls } from 'three/examples/jsm/controls/TransformControls';

import "./index.scss";

export default (): JSX.Element => {
  useEffect(() => {
    // ----------场景
    const scene = new THREE.Scene(); // 场景
    const geometry = new THREE.SphereGeometry(60, 40, 40); // 创建几何球体
    // const geometry = new THREE.BoxGeometry(10, 100, 100) // 创建几何立方体

    const material = new THREE.MeshLambertMaterial({ color: 0xff0000 }); // 材质对象
    const mesh = new THREE.Mesh(geometry, material); // 网格对象 
    scene.add(mesh); // 将网格对象添加到场景中

    const mesh1 = new THREE.Mesh(geometry, material);
    mesh1.position.x = 140;
    mesh1.position.y = 140;
    mesh1.position.z = 140;
    scene.add(mesh1);

    const point = new THREE.PointLight(0xffffff); // 点光源
    point.position.set(400, 200, 300); // 点光源位置
    scene.add(point); // 点光源添加到场景中

    const ambient = new THREE.AmbientLight(0x444444); // 环光源
    scene.add(ambient);

    // ----------相机
    const w = window.innerWidth;
    const h = window.innerHeight;
    const k = w / h;
    const s = 200; // 三维场景显示范围控制系数，越大显示范围越大
    const camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000); // 相机对象
    camera.position.set(200, 300, 200); // 相机位置
    camera.lookAt(scene.position); // 相机方向（横向场景对象）

    // ----------渲染器
    const renderer = new THREE.WebGL1Renderer();

    // 控制器
    let controls1 = new OrbitControls(camera, renderer.domElement);

    // 创建TransformControls控件
    let controls = new TransformControls(camera, renderer.domElement);
    // 将控件添加到场景中
    scene.add(controls);
    // 将控件设置为操作球体
    controls.attach(mesh);
    // 变换控制器最新的信息
    controls.addEventListener('objectChange', (e) => console.log(controls.object))
    // 变换控制器动起来时候禁止另一个控制器的功能
    controls.addEventListener('mouseDown', () => controls1.enabled = false)
    controls.addEventListener('mousUp', () => controls1.enabled = true)

    renderer.setSize(w, h); // 设置渲染区域尺寸
    // renderer.setClearColor(0xb9d3ff, 1); // 设置背景色默认黑色
    document.body.appendChild(renderer.domElement); // 添加canvas到html中
    // renderer.render(scene, camera); // 通过场景和相机参数渲染
    const render = () => {
        requestAnimationFrame(render);
        renderer.render(scene, camera)
    }
    render();
    controls1.addEventListener('change', () => renderer.render(scene, camera))
    return () => {
      document.body.removeChild(renderer.domElement); // 添加canvas到html中
    }
  }, []);
  return <div>第一个3d场景</div>;
};
